﻿using Microsoft.AspNetCore.Mvc;
using QRCoder;
using ScanQrCodeDemo.Web.Models;
using ScanQrCodeDemo.Web.Utility;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ScanQrCodeDemo.Web.Controllers
{

    public class AccountController : Controller
    {
        private readonly RedisHelper redis;

        public AccountController(RedisHelper redis)
        {
            this.redis = redis;
        }

        [Route("/qrcode/{id}")]
        public IActionResult QRCode(string id)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(id, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20);
            MemoryStream memoryStream = new MemoryStream();
            qrCodeImage.Save(memoryStream, ImageFormat.Png);
            return File(memoryStream.GetBuffer(), "image/png");
        }

        [Route("/GetSession/{id}")]
        public JsonResult GetQRCodeLoginSession(Guid id)
        {
            var session = redis.GetSession(id);
            return Json(session);
        }

        [Route("/SetSessionState/{id}")]
        public JsonResult SetQRCodeSessionState(Guid id)
        {
            redis.UpdateScanState(id);
            return Json(new AjaxResult());
        }

        [Route("/SetSessionLogin")]
        public JsonResult SetQRCodeSessionLogin(Guid id, string userId)
        {
            redis.Login(id, userId);
            return Json(new AjaxResult());
        }

        [Route("/LoginWithId")]
        public IActionResult LoginWithId(Guid id, string userId)
        {
            var session = redis.GetSession(id);
            if (session != null && session.UserId == userId)
            {
                return Redirect("/");
            }
            return Redirect("/LoginFailed");
        }

    }
}
